package com.lifeverse.service;

import com.lifeverse.entity.Decision;
import com.lifeverse.entity.LifeEntity;
import com.lifeverse.service.DecisionEngine.DecisionExecutionResult;
import com.lifeverse.service.DecisionEngine.DecisionOption;
import com.lifeverse.util.JsonUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 决策执行器
 * 负责执行决策方案
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DecisionExecutor {
    
    private final Random random = new Random();
    
    /**
     * 执行决策
     */
    public DecisionExecutionResult execute(Decision decision) {
        log.debug("执行决策 - ID: {}, 标题: {}", decision.getId(), decision.getTitle());
        
        try {
            // 解析选择的决策选项
            DecisionOption chosenOption = JsonUtils.fromJson(decision.getChosenOption(), DecisionOption.class);
            if (chosenOption == null) {
                return createFailedResult("无法解析决策选项");
            }
            
            // 根据决策类型执行相应的操作
            DecisionExecutionResult result = executeByType(decision, chosenOption);
            
            log.debug("决策执行完成 - ID: {}, 结果: {}", decision.getId(), 
                     result.isSuccess() ? "成功" : "失败");
            
            return result;
            
        } catch (Exception e) {
            log.error("决策执行异常 - ID: {}", decision.getId(), e);
            return createFailedResult("执行异常: " + e.getMessage());
        }
    }
    
    /**
     * 根据决策类型执行
     */
    private DecisionExecutionResult executeByType(Decision decision, DecisionOption chosenOption) {
        switch (decision.getType()) {
            case RESOURCE_ALLOCATION:
                return executeResourceAllocation(decision, chosenOption);
            case COLLABORATION:
                return executeCollaboration(decision, chosenOption);
            case EVOLUTION:
                return executeEvolution(decision, chosenOption);
            case RELATIONSHIP:
                return executeRelationship(decision, chosenOption);
            case SYSTEM_OPTIMIZATION:
                return executeSystemOptimization(decision, chosenOption);
            case RISK_MANAGEMENT:
                return executeRiskManagement(decision, chosenOption);
            case INNOVATION:
                return executeInnovation(decision, chosenOption);
            case VALUE_ASSESSMENT:
                return executeValueAssessment(decision, chosenOption);
            default:
                return executeDefault(decision, chosenOption);
        }
    }
    
    /**
     * 执行资源分配决策
     */
    private DecisionExecutionResult executeResourceAllocation(Decision decision, DecisionOption chosenOption) {
        log.debug("执行资源分配决策 - 选项: {}", chosenOption.getName());
        
        LifeEntity lifeEntity = decision.getLifeEntity();
        Map<String, Object> results = new HashMap<>();
        
        // 模拟资源分配执行
        BigDecimal currentEnergy = lifeEntity.getEnergyLevel();
        BigDecimal energyCost = calculateEnergyCost(chosenOption);
        
        if (currentEnergy.compareTo(energyCost) < 0) {
            return createFailedResult("能量不足，无法执行资源分配");
        }
        
        // 执行资源分配
        BigDecimal newEnergyLevel = currentEnergy.subtract(energyCost);
        lifeEntity.setEnergyLevel(newEnergyLevel);
        
        // 计算资源分配效果
        BigDecimal allocationEfficiency = calculateAllocationEfficiency(chosenOption, lifeEntity);
        BigDecimal actualImpact = allocationEfficiency.multiply(BigDecimal.valueOf(10));
        
        results.put("energyCost", energyCost);
        results.put("allocationEfficiency", allocationEfficiency);
        results.put("newEnergyLevel", newEnergyLevel);
        
        return createSuccessResult(actualImpact, results);
    }
    
    /**
     * 执行协作决策
     */
    private DecisionExecutionResult executeCollaboration(Decision decision, DecisionOption chosenOption) {
        log.debug("执行协作决策 - 选项: {}", chosenOption.getName());
        
        LifeEntity lifeEntity = decision.getLifeEntity();
        Map<String, Object> results = new HashMap<>();
        
        // 模拟协作执行
        BigDecimal collaborationScore = lifeEntity.getCollaborationScore();
        BigDecimal collaborationBonus = calculateCollaborationBonus(chosenOption, collaborationScore);
        
        // 更新协作能力
        BigDecimal newCollaborationScore = collaborationScore.add(collaborationBonus);
        lifeEntity.setCollaborationScore(newCollaborationScore.min(BigDecimal.valueOf(100)));
        
        // 计算协作效果
        BigDecimal actualImpact = collaborationBonus.multiply(BigDecimal.valueOf(5));
        
        results.put("collaborationBonus", collaborationBonus);
        results.put("newCollaborationScore", newCollaborationScore);
        results.put("collaborationPartners", generateCollaborationPartners());
        
        return createSuccessResult(actualImpact, results);
    }
    
    /**
     * 执行进化决策
     */
    private DecisionExecutionResult executeEvolution(Decision decision, DecisionOption chosenOption) {
        log.debug("执行进化决策 - 选项: {}", chosenOption.getName());
        
        LifeEntity lifeEntity = decision.getLifeEntity();
        Map<String, Object> results = new HashMap<>();
        
        // 模拟进化执行
        if (lifeEntity.getConsciousnessLevel().canUpgrade()) {
            lifeEntity.evolve();
            
            // 提升各项能力
            BigDecimal wisdomIncrease = BigDecimal.valueOf(random.nextInt(20) + 10);
            BigDecimal creativityIncrease = BigDecimal.valueOf(random.nextInt(15) + 5);
            
            lifeEntity.setWisdomScore(lifeEntity.getWisdomScore().add(wisdomIncrease));
            lifeEntity.setCreativityScore(lifeEntity.getCreativityScore().add(creativityIncrease));
            
            BigDecimal actualImpact = wisdomIncrease.add(creativityIncrease);
            
            results.put("wisdomIncrease", wisdomIncrease);
            results.put("creativityIncrease", creativityIncrease);
            results.put("newConsciousnessLevel", lifeEntity.getConsciousnessLevel());
            
            return createSuccessResult(actualImpact, results);
        } else {
            return createFailedResult("当前意识水平无法进化");
        }
    }
    
    /**
     * 执行关系决策
     */
    private DecisionExecutionResult executeRelationship(Decision decision, DecisionOption chosenOption) {
        log.debug("执行关系决策 - 选项: {}", chosenOption.getName());
        
        Map<String, Object> results = new HashMap<>();
        
        // 模拟关系建立或维护
        String relationshipType = determineRelationshipType(chosenOption);
        Integer relationshipStrength = random.nextInt(50) + 50; // 50-100
        
        BigDecimal actualImpact = BigDecimal.valueOf(relationshipStrength * 0.5);
        
        results.put("relationshipType", relationshipType);
        results.put("relationshipStrength", relationshipStrength);
        results.put("relationshipPartner", "LifeEntity_" + random.nextInt(1000));
        
        return createSuccessResult(actualImpact, results);
    }
    
    /**
     * 执行系统优化决策
     */
    private DecisionExecutionResult executeSystemOptimization(Decision decision, DecisionOption chosenOption) {
        log.debug("执行系统优化决策 - 选项: {}", chosenOption.getName());
        
        LifeEntity lifeEntity = decision.getLifeEntity();
        Map<String, Object> results = new HashMap<>();
        
        // 模拟系统优化
        BigDecimal optimizationGain = BigDecimal.valueOf(random.nextInt(30) + 10);
        BigDecimal newHealthScore = lifeEntity.getHealthScore().add(optimizationGain);
        lifeEntity.setHealthScore(newHealthScore.min(BigDecimal.valueOf(100)));
        
        BigDecimal actualImpact = optimizationGain;
        
        results.put("optimizationGain", optimizationGain);
        results.put("newHealthScore", newHealthScore);
        results.put("optimizedComponents", generateOptimizedComponents());
        
        return createSuccessResult(actualImpact, results);
    }
    
    /**
     * 执行风险管理决策
     */
    private DecisionExecutionResult executeRiskManagement(Decision decision, DecisionOption chosenOption) {
        log.debug("执行风险管理决策 - 选项: {}", chosenOption.getName());
        
        Map<String, Object> results = new HashMap<>();
        
        // 模拟风险管理
        BigDecimal riskReduction = BigDecimal.valueOf(random.nextInt(40) + 20);
        String riskType = determineRiskType(decision);
        
        BigDecimal actualImpact = riskReduction.multiply(BigDecimal.valueOf(0.8));
        
        results.put("riskReduction", riskReduction);
        results.put("riskType", riskType);
        results.put("mitigationMeasures", generateMitigationMeasures());
        
        return createSuccessResult(actualImpact, results);
    }
    
    /**
     * 执行创新决策
     */
    private DecisionExecutionResult executeInnovation(Decision decision, DecisionOption chosenOption) {
        log.debug("执行创新决策 - 选项: {}", chosenOption.getName());
        
        LifeEntity lifeEntity = decision.getLifeEntity();
        Map<String, Object> results = new HashMap<>();
        
        // 创新决策有一定失败概率
        boolean innovationSuccess = random.nextDouble() > 0.3; // 70%成功率
        
        if (innovationSuccess) {
            BigDecimal creativityBonus = BigDecimal.valueOf(random.nextInt(25) + 15);
            lifeEntity.setCreativityScore(lifeEntity.getCreativityScore().add(creativityBonus));
            
            BigDecimal actualImpact = creativityBonus.multiply(BigDecimal.valueOf(1.5));
            
            results.put("creativityBonus", creativityBonus);
            results.put("innovationType", "BREAKTHROUGH");
            results.put("innovationValue", actualImpact);
            
            return createSuccessResult(actualImpact, results);
        } else {
            return createFailedResult("创新尝试失败");
        }
    }
    
    /**
     * 执行价值评估决策
     */
    private DecisionExecutionResult executeValueAssessment(Decision decision, DecisionOption chosenOption) {
        log.debug("执行价值评估决策 - 选项: {}", chosenOption.getName());
        
        Map<String, Object> results = new HashMap<>();
        
        // 模拟价值评估
        BigDecimal assessedValue = BigDecimal.valueOf(random.nextInt(100) + 50);
        String valueCategory = determineValueCategory(decision);
        
        BigDecimal actualImpact = assessedValue.multiply(BigDecimal.valueOf(0.3));
        
        results.put("assessedValue", assessedValue);
        results.put("valueCategory", valueCategory);
        results.put("assessmentMethod", chosenOption.getSource());
        
        return createSuccessResult(actualImpact, results);
    }
    
    /**
     * 执行默认决策
     */
    private DecisionExecutionResult executeDefault(Decision decision, DecisionOption chosenOption) {
        log.debug("执行默认决策 - 选项: {}", chosenOption.getName());
        
        Map<String, Object> results = new HashMap<>();
        
        // 默认执行，影响较小
        BigDecimal actualImpact = BigDecimal.valueOf(random.nextInt(20) + 5);
        
        results.put("executionType", "DEFAULT");
        results.put("impact", actualImpact);
        
        return createSuccessResult(actualImpact, results);
    }
    
    /**
     * 计算能量消耗
     */
    private BigDecimal calculateEnergyCost(DecisionOption option) {
        switch (option.getSource()) {
            case "INNOVATION":
                return BigDecimal.valueOf(random.nextInt(20) + 15); // 15-35
            case "RULE":
                return BigDecimal.valueOf(random.nextInt(10) + 5);  // 5-15
            case "HISTORY":
                return BigDecimal.valueOf(random.nextInt(15) + 8);  // 8-23
            case "DEFAULT":
                return BigDecimal.valueOf(random.nextInt(8) + 2);   // 2-10
            default:
                return BigDecimal.valueOf(10);
        }
    }
    
    /**
     * 计算分配效率
     */
    private BigDecimal calculateAllocationEfficiency(DecisionOption option, LifeEntity lifeEntity) {
        BigDecimal baseEfficiency = BigDecimal.valueOf(0.6 + random.nextDouble() * 0.3); // 0.6-0.9
        
        // 根据生命体智慧调整效率
        BigDecimal wisdomFactor = lifeEntity.getWisdomScore().divide(BigDecimal.valueOf(1000), 2, java.math.RoundingMode.HALF_UP);
        
        return baseEfficiency.add(wisdomFactor).min(BigDecimal.valueOf(1.0));
    }
    
    /**
     * 计算协作奖励
     */
    private BigDecimal calculateCollaborationBonus(DecisionOption option, BigDecimal currentScore) {
        BigDecimal baseBonus = BigDecimal.valueOf(random.nextInt(10) + 5);
        
        // 当前协作分数越低，提升空间越大
        if (currentScore.compareTo(BigDecimal.valueOf(50)) < 0) {
            baseBonus = baseBonus.multiply(BigDecimal.valueOf(1.5));
        }
        
        return baseBonus;
    }
    
    /**
     * 生成协作伙伴
     */
    private String[] generateCollaborationPartners() {
        int partnerCount = random.nextInt(3) + 1;
        String[] partners = new String[partnerCount];
        for (int i = 0; i < partnerCount; i++) {
            partners[i] = "Partner_" + random.nextInt(1000);
        }
        return partners;
    }
    
    /**
     * 生成优化组件
     */
    private String[] generateOptimizedComponents() {
        String[] components = {"Memory", "Processing", "Network", "Storage", "Interface"};
        int componentCount = random.nextInt(3) + 1;
        String[] optimized = new String[componentCount];
        for (int i = 0; i < componentCount; i++) {
            optimized[i] = components[random.nextInt(components.length)];
        }
        return optimized;
    }
    
    /**
     * 确定关系类型
     */
    private String determineRelationshipType(DecisionOption option) {
        String[] types = {"COOPERATION", "MENTORSHIP", "PARTNERSHIP", "ALLIANCE", "FRIENDSHIP"};
        return types[random.nextInt(types.length)];
    }
    
    /**
     * 确定风险类型
     */
    private String determineRiskType(Decision decision) {
        String[] types = {"OPERATIONAL", "STRATEGIC", "FINANCIAL", "TECHNICAL", "ENVIRONMENTAL"};
        return types[random.nextInt(types.length)];
    }
    
    /**
     * 生成缓解措施
     */
    private String[] generateMitigationMeasures() {
        String[] measures = {"Monitoring", "Backup_Plan", "Insurance", "Diversification", "Training"};
        int measureCount = random.nextInt(3) + 1;
        String[] selected = new String[measureCount];
        for (int i = 0; i < measureCount; i++) {
            selected[i] = measures[random.nextInt(measures.length)];
        }
        return selected;
    }
    
    /**
     * 确定价值类别
     */
    private String determineValueCategory(Decision decision) {
        String[] categories = {"ECONOMIC", "SOCIAL", "ENVIRONMENTAL", "STRATEGIC", "INNOVATION"};
        return categories[random.nextInt(categories.length)];
    }
    
    /**
     * 创建成功结果
     */
    private DecisionExecutionResult createSuccessResult(BigDecimal actualImpact, Map<String, Object> results) {
        DecisionExecutionResult result = new DecisionExecutionResult();
        result.setSuccess(true);
        result.setActualImpact(actualImpact);
        result.setResults(results);
        return result;
    }
    
    /**
     * 创建失败结果
     */
    private DecisionExecutionResult createFailedResult(String errorMessage) {
        DecisionExecutionResult result = new DecisionExecutionResult();
        result.setSuccess(false);
        result.setErrorMessage(errorMessage);
        result.setActualImpact(BigDecimal.ZERO);
        return result;
    }
}